#

import pymysql

import pymysql


class MysqlDB:



   def __init__(self) -> None:
      super().__init__()
      db = pymysql.connect("47.105.166.188", "root", "chenwuHS", "unify")
      self.db = db
      self.cursor = db.cursor()

   '''
   保存sql
   '''
   def save(self, sql):
      try:
         # 执行sql语句
         self.cursor.execute(sql)
         # 提交到数据库执行
         self.db.commit()
         insertId = self.cursor.lastrowid
         print("insert id is", insertId)
         return insertId
      except BaseException as e:
         print(e)
         # 如果发生错误则回滚
         self.db.rollback()
         return 0

   '''
   更新sql
   '''
   def update(self, sql):
      try:
         # 执行sql语句
         self.cursor.execute(sql)
         # 提交到数据库执行
         return self.db.commit()
      except BaseException as e:
         print(sql)
         print(e)
         # 如果发生错误则回滚
         self.db.rollback()
         return 0

   def closeDB(self):
      # 关闭数据库连接
      self.db.close()


   def query(self, sql):
      try:
         # 执行SQL语句
         self.cursor.execute(sql)
         # 获取所有记录列表
         return self.cursor.fetchall()
         # for row in results:
         #    fname = row[0]
         #    lname = row[1]
         #    age = row[2]
         #    sex = row[3]
         #    income = row[4]
         #    # 打印结果
         #    print("fname=%s,lname=%s,age=%d,sex=%s,income=%d" % \
         #          (fname, lname, age, sex, income))
      except BaseException as e:
         print("Error: unable to fecth data", e)
         return

   def commit(self):
      self.db.commit()

   def rollback(self):
      self.db.rollback()

   @staticmethod
   def dealStr(content):
      return pymysql.escape_string(content)